/**
 * <p>Copyright (c) 2010 by DRM. </p>
 */

package com.android.drm;

import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.android.drm.help.CustomDialog;
import com.android.drm.to.User;

/**
 * <p>
 * <b>CLASS:</b> com.android.drm.ManageUser
 * </p>
 * 
 * ...........................................................................
 * <p>
 * <b>DESCRIPTION:</b><br/>
 * this class performs creating and deleting a user and displays the current user list.
 * </p>
 * 
 * ...........................................................................
 * <p>
 * <b>MODIFICATION HISTORY:</b>
 * <p>
 * [07/29/10] emily gu: Initial version.
 * </p>
 * </p>
 * 
 * ...........................................................................
 * 
 * @author emily gu
 * @since 1.0
 */

public class ManageUser extends Activity {
	private static final int HELP_DIALOG = 1;
	private static final int ABOUT_DIALOG = 2;
	private final static String CREATE_USER = "Create User";
	private EditText userNameBox;
	private EditText ageBox;
	private ListView listView;
	private DRMApplication drmApplication;
	private UserAdapter dataAdapter;
	private List<User> userList;

	@Override
	public void onCreate(final Bundle savedInstanceState) {
		Log.d(CREATE_USER, "onCreate");
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.manage_user);
		
		drmApplication = (DRMApplication) this.getApplication();
		
		userList = this.drmApplication.getDataHelper().selectUsers();

		this.userNameBox = (EditText) this.findViewById(R.id.user_name_box);
		this.ageBox = (EditText)this.findViewById(R.id.age_box);
		this.listView = (ListView) this.findViewById(R.id.ListView01);
		this.dataAdapter = new UserAdapter(this, R.layout.row, userList);
		listView.setAdapter(dataAdapter);
	}
	
	public void myClickHandler (View v) {
			switch (v.getId()) {
				case R.id.createButton: 
					String _userName = ManageUser.this.userNameBox.getText().toString();
					String _age = ManageUser.this.ageBox.getText().toString();
					new InsertDataTask().execute(_userName,_age);
				
					User _user = new User(new Integer(_age), _userName);
					ManageUser.this.dataAdapter.add(_user);
					break;
				case R.id.deleteButton:
					_userName = ManageUser.this.userNameBox.getText().toString();
					new DeleteDataTask().execute(_userName);
					
					_user = new User(_userName);
					ManageUser.this.dataAdapter.remove(_user);
					break;
				case R.id.helpButton:
					ManageUser.this.showDialog(HELP_DIALOG);
					break;
				case R.id.logo:
					ManageUser.this.showDialog(ABOUT_DIALOG);		
					break;
				case R.id.homeButton:
		            Intent intent = new Intent(ManageUser.this, HomeScreen.class);
		            intent.putExtra("userChanged", true);
		            intent.putExtra("userC", "true");
		            intent.putExtra("userCl", 1);
		            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); 
		            startActivity(intent);
					break;
				default:
					break;
			}
	}

	private class InsertDataTask extends AsyncTask<String, Void, Void> {
		private final ProgressDialog dialog = new ProgressDialog(
				ManageUser.this);

		protected void onPreExecute() {
			this.dialog.setMessage("Inserting user...");
			this.dialog.show();
		}

		// automatically done on worker thread (separate from UI thread)
		protected Void doInBackground(final String... args) {
			try {
				ManageUser.this.drmApplication.getDataHelper().insertUser(
						args[0], Long.valueOf(args[1]));
			} catch (Exception e) {
				Log.d("Insertion Error:", e.getMessage());
			}
			return null;
		}

		protected void onPostExecute(final Void result) {
			if (this.dialog.isShowing()) {
				this.dialog.dismiss();
			}
		}
	}

	private class DeleteDataTask extends AsyncTask<String, Void, Long> {
		private final ProgressDialog dialog = new ProgressDialog(
				ManageUser.this);

		protected void onPreExecute() {
			this.dialog.setMessage("Deleting user...");
			this.dialog.show();
		}

		protected Long doInBackground(final String... args) {
			long id = 0;
			try {
				id = ManageUser.this.drmApplication.getDataHelper().deleteUser(
						args[0]);
			} catch (Exception e) {
				Log.d("Deletion Error:", e.getMessage());
			}
			return id;
		}

		protected void onPostExecute(final Long result) {
			if (this.dialog.isShowing()) {
				this.dialog.dismiss();
			}
		}
	}

	private class UserAdapter extends ArrayAdapter<User> {

		private List<User> items;

		public UserAdapter(Context context, int textViewResourceId,
				List<User> items) {
			super(context, textViewResourceId, items);
			this.items = items;
		}

		public void add(User item) {
			items.add(item);
			this.notifyDataSetChanged();
		}

		public void remove(User item) {
			items.remove(item);
			this.notifyDataSetChanged();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.row, null);
			}
			User u = items.get(position);
			if (u != null) {
				TextView tt = (TextView) v.findViewById(R.id.toptext);
				TextView bt = (TextView) v.findViewById(R.id.bottomtext);
				if (tt != null) {
					tt.setText(getString(R.string.name) + u.getUserName());
				}
				if (bt != null) {
					bt.setText(getString(R.string.age)+ u.getAge());
				}
			}
			return v;
		}
	}
	
    public Dialog onCreateDialog(int dialogId) {
    	Dialog dialog = null;
    	switch (dialogId) {
	    	case HELP_DIALOG :
				CustomDialog.Builder customBuilder = new
				CustomDialog.Builder(ManageUser.this);
				customBuilder.setMessage(R.string.ManageUserHelpMsg)
					.setPositiveButton("Close", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
	            dialog = customBuilder.create();
	    		break;
	    	case ABOUT_DIALOG : 
				CustomDialog.Builder aboutBuilder = new
				CustomDialog.Builder(ManageUser.this);
				aboutBuilder.setMessage(R.string.AboutMsg)
					.setPositiveButton("Close", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
	            dialog = aboutBuilder.create();
	    		break;
    	}
    	return dialog;
    }
	
}